//
//  PMineResumeCredentViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/24.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "PMineResumeCredentViewController.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "ImageCollectionViewCell.h"

@interface PMineResumeCredentViewController ()<TimeSelectPickerViewDelegate, PSSingleRowViewDelegate, ImageCollectionViewCellDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate>
{
    BaseNetManager *netManager;
    
    UIScrollView *bottomScrollView;
    UIButton *updateBtn;
}
@property (nonatomic, strong) PSCell *nameCell;
@property (nonatomic, strong) PSCell *startTimeCell;
@property (nonatomic, strong) TimeSelectPickerView *startTimePickerView;
@property (nonatomic, strong) PSSingleRowView *updateImgPickerView;
@end

@implementation PMineResumeCredentViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.startTimePickerView) {
        self.startTimePickerView.hidden = YES;
    }
    if (self.updateImgPickerView) {
        self.updateImgPickerView.hidden = YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"职称证书";
    netManager = [BaseNetManager sharedManager];
    
    if (self.type == AddOrEditTypeOfEdit) {
        [self loadData];
    } else {
        self.model = [[PMineResumeCredentInfoModel alloc] init];
        [self initUI];
    }
}
- (void)loadData {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:self.model.info_id forKey:@"info_id"];
    
    [BaseNetManager requestWithMethod:POST path:PersonMine_GetCredentInfo_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            if ([data isKindOfClass:[NSArray class]]) {
                self.model = [[PMineResumeCredentInfoModel alloc] init];
                [self.model setValuesForKeysWithDictionary:data[0]];
            } else if ([data isKindOfClass:[NSDictionary class]]) {
                self.model = [[PMineResumeCredentInfoModel alloc] init];
                [self.model setValuesForKeysWithDictionary:data];
            }
            
            [self initUI];
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
        [self loadData];
    }];
}
- (void)initUI {
    UIButton *okBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-50*Scale, HeightOfStatusBar+3*Scale, 50*Scale, 36) imageName:nil target:self action:@selector(okBtnTap) title:((self.type == AddOrEditTypeOfAdd)?@"确定":@"保存") titleColor:THEMECOLOR_OF_ORANGE];
    okBtn.titleLabel.font = Font(Font_15);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:okBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    bottomScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-SIMEmojKeyBoardkBottomNOSafeArea_Height-HeightOfStatusBarAndNavigationBar)];
    [self.view addSubview:bottomScrollView];
    
    __weak __typeof(self)weakSelf = self;
    self.startTimePickerView = [[TimeSelectPickerView alloc] initWithTarget:self time:nil timeSelectPickerType:TimeSelectPickerTypeOfWorking dateFormat:nil];
    self.startTimePickerView.hidden = YES;
    NSMutableArray *headerArray = [NSMutableArray arrayWithCapacity:0];
    PublicCategoryElementModel *model1 = [[PublicCategoryElementModel alloc] init];
    [model1 setValuesForKeysWithDictionary:@{@"id":@"0", @"name":@"拍摄"}];
    [headerArray addObject:model1];
    PublicCategoryElementModel *model2 = [[PublicCategoryElementModel alloc] init];
    [model2 setValuesForKeysWithDictionary:@{@"id":@"1", @"name":@"相册"}];
    [headerArray addObject:model2];
    self.updateImgPickerView = [[PSSingleRowView alloc] initWithData:headerArray target:self];
    self.updateImgPickerView.hidden = YES;
    
    self.nameCell = [[PSCell alloc] initWithFrame:CGRectMake(30*Scale, 15*Scale, WIDTH-60*Scale, PSCellHeight) title:@"职称证书" text:((self.model&&self.model.name.length)?self.model.name:nil) placeholder:@"请输入职称证书" cellType:PSCellTypeOfWriteonly];
    self.nameCell.textField.delegate = self;
    [bottomScrollView addSubview:self.nameCell];
    
    self.startTimeCell = [[PSCell alloc] initWithFrame:CGRectMake(30*Scale, EndY(self.nameCell), WIDTH-60*Scale, PSCellHeight) title:@"获得时间" text:((self.type == AddOrEditTypeOfEdit)?self.model.recieve_date:nil) placeholder:@"年/月/日" cellType:PSCellTypeOfIndicator];
    self.startTimeCell.tap = ^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [UIToolsControl resignFirstResponderForTextField:strongSelf.nameCell.textField];
        strongSelf.startTimePickerView.hidden = NO;
    };
    [bottomScrollView addSubview:self.startTimeCell];
    
    UILabel *topLbl = [UIToolsControl initLabelWithFrame:CGRectMake(30*Scale, EndY(self.startTimeCell)+10*Scale, 200, 40*Scale) text:@"证书上传" textColor:THEMECOLOR_OF_TEXT_333333 font:Font_13];
    [bottomScrollView addSubview:topLbl];
    
    updateBtn = [UIToolsControl initButtonWithFrame:CGRectMake(StartX(self.nameCell), EndY(topLbl), 110*Scale, 110*Scale) imageName:@"" target:self action:@selector(updateBtnTap) title:nil titleColor:nil];
    [updateBtn setBackgroundImage:[UIImage imageNamed:@"update_icon"] forState:UIControlStateNormal];
    [self.view addSubview:updateBtn];
    if (self.model && self.model.images.length) {
        [updateBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.model.images] forState:UIControlStateNormal];
    }
    
    if (self.type == AddOrEditTypeOfEdit) {
        UIButton *deleteBtn = [UIToolsControl initButtonWithFrame:CGRectMake(40*Scale, EndY(updateBtn)+30*Scale, WIDTH-80*Scale, 40*Scale) imageName:nil target:self action:@selector(deleteBtnTap) title:@"删除此条经历" titleColor:COLOR_OF_WHITE];
        deleteBtn.backgroundColor = THEMECOLOR_OF_RED;
        deleteBtn.layer.cornerRadius = 20*Scale;
        deleteBtn.layer.masksToBounds = YES;
        deleteBtn.titleLabel.font = Font(Font_17);
        [bottomScrollView addSubview:deleteBtn];
        
        bottomScrollView.contentSize = CGSizeMake(0, EndY(deleteBtn)+20*Scale);
    } else {
        bottomScrollView.contentSize = CGSizeMake(0, EndY(updateBtn)+20*Scale);
    }
}
- (void)okBtnTap {
    [UIToolsControl resignFirstResponderForTextField:self.nameCell.textField];
    if (self.nameCell.textField.text.length) {
        if (self.startTimeCell.textField.text.length) {
            SVPHUDShow;
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
            dic = [UIToolsControl getPublicParameter];
            [dic setObject:((self.model && self.model.info_id.length)?self.model.info_id:@"") forKey:@"info_id"];
            [dic setObject:((self.startTimeCell.textField.text.length<=7)?self.startTimeCell.textField.text:[self.startTimeCell.textField.text substringToIndex:7]) forKey:@"recieve_date"];
            [dic setObject:self.nameCell.textField.text forKey:@"name"];
            [dic setObject:((self.model&&self.model.images.length)?self.model.images:@"") forKey:@"images"];
            
            [BaseNetManager requestWithMethod:POST path:PersonMine_SaveCredentInfo_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
                if ([responseObject[@"code"] integerValue] == 2000) {
                    SVPHUDSuccess(responseObject[@"msg"]);
                    
                    if (self.delegate && [self.delegate respondsToSelector:@selector(pMineResumeCredentViewControllerBackRefresh:)]) {
                        [self.delegate pMineResumeCredentViewControllerBackRefresh:YES];
                    }
                    [self performSelector:@selector(delayClick) withObject:nil afterDelay:0.5];
                } else {
                    SVPHUDError(responseObject[@"msg"]);
                }
            } failurBlock:^(NSError * _Nonnull error) {
                SVPHUDError(NetErrorAlertText);
            }];
        } else {
            SVPHUDError(StartTimeOKAlertText);
        }
    } else {
        SVPHUDError(CredentAlertText);
    }
}
- (void)delayClick {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)updateBtnTap {
    [UIToolsControl resignFirstResponderForTextField:self.nameCell.textField];
    self.updateImgPickerView.hidden = NO;
}
- (void)imageCollectionViewCellImgTap:(NSIndexPath *)indexPath {
    self.updateImgPickerView.hidden = NO;
}
- (void)psSingleRowViewCancel:(PSSingleRowView *)psSingleRowView {
    psSingleRowView.hidden = YES;
}
- (void)psSingleRowViewOk:(PublicCategoryElementModel *)model PSSingleRowView:(PSSingleRowView *)psSingleRowView {
    psSingleRowView.hidden = YES;
    if (psSingleRowView == self.updateImgPickerView) {
        if ([model.id integerValue] == 1) { // 相册
            [self openPhotoLibrary];
        } else { // 拍摄
            [self openCamera];
        }
    }
}
- (void)timeSelectPickerViewCancel:(TimeSelectPickerView *)timeSelectPickerView {
    timeSelectPickerView.hidden = YES;
}
- (void)timeSelectPickerViewOK:(NSString *)selectText timeSelectPickerView:(TimeSelectPickerView *)timeSelectPickerView {
    timeSelectPickerView.hidden = YES;
    if (timeSelectPickerView == self.startTimePickerView) {
        self.startTimeCell.textField.text = selectText;
    }
}
- (void)openCamera {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) { // 无权限
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"相机权限未开启" message:@"相机权限未开启，请进入系统【设置】>【隐私】>【相机】中打开开关,开启相机功能" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:170];
        alertView.resultIndex = ^(NSInteger index) { //回调---处理一系列动作
            if (index == 2) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
        [alertView showXLAlertView];
    } else { // 有权限
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
}
- (void)openPhotoLibrary {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) { // 无权限
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"相册权限未开启" message:@"相册权限未开启，请进入系统【设置】>【隐私】>【相册】中打开开关,开启相册功能" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:170];
        alertView.resultIndex = ^(NSInteger index) { //回调---处理一系列动作
            if (index == 2) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
        [alertView showXLAlertView];
    } else { // 有权限
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.allowsEditing = NO;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.navigationBar.translucent = NO;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:imagePicker animated:YES completion:^{
            NSLog(@"打开相册");
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSLog(@"finish..");
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    SVPHUDShow;
    [DataToolsControl uploadImgType:UploadImgTypeOfResumeCredent image:image successBlock:^(NSDictionary *responseObject) {
        SVPHUDDismiss;
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            self.model.images = [UIToolsControl dataAnalysis:data[@"url"]];
            [self->updateBtn setBackgroundImage:image forState:UIControlStateNormal];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(@"上传失败，请重新操作");
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)deleteBtnTap {
    CustomView *alertView = [[CustomView alloc] initWithTitle:@"提示" message:@"确认删除此条经历" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:150];
    alertView.resultIndex = ^(NSInteger index){
        //回调---处理一系列动作
        if (index == 2) {
            [self deleteClick];
        }
    };
    [alertView showXLAlertView];
}
- (void)deleteClick {
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:self.model.info_id forKey:@"info_id"];
    
    [BaseNetManager requestWithMethod:POST path:PersonMine_DelCredentInfo_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            SVPHUDSuccess(responseObject[@"msg"]);
            if (self.delegate && [self.delegate respondsToSelector:@selector(pMineResumeCredentViewControllerBackRefresh:)]) {
                [self.delegate pMineResumeCredentViewControllerBackRefresh:YES];
            }
            [self performSelector:@selector(delayClick) withObject:nil afterDelay:0.5];
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
        SVPHUDError(NetErrorAlertText);
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [UIToolsControl resignFirstResponderForTextField:self.nameCell.textField];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end
